<template>
  <el-dialog
    v-model="visible"
    title="拓扑配置"
    width="80%"
    :before-close="handleClose"
  >
    <GapedColumn width="100%">
      <GapedRow>
        <el-button @click="saveTopoConfig">保存</el-button>
      </GapedRow>
      <TopologyComponent
        ref="topoRef"
        :node-business-data="nodeBusinessData"
        :nodeUIData="nodeUIData"
        :categories="sections"
        @update:nodeBusinessData="handleBusinessDataUpdate"
        @update:nodeUIData="handleUIDataUpdate"
      />
    </GapedColumn>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import TopologyComponent from '@/components/topo/TopologyComponent.vue'
import { GapedColumn, GapedRow } from '@/core/components'
import useApi from '@/core/apiStore'
import type { NodeBusinessData, NodeUIData } from '@/components/topo/types'
import { showSuccessSaveMessage } from '@/utils'
import useTopoData from './useTopoData'

const { sections, nodeBusinessData, nodeUIData, loadTopoData } = useTopoData()

const apiStore = useApi()
const topoRef = ref(null)

const handleBusinessDataUpdate = (data: NodeBusinessData[]) => {
  console.log('Business data updated:', data)
}

const handleUIDataUpdate = (data: NodeUIData[]) => {
  console.log('UI data updated:', data)
}

const visible = ref(false)
const businessName = ref('')
const saveTopoConfig = async () => {
  const topoConfig = topoRef.value.save()
  await apiStore.setBusinessNodes({
    businessName: businessName.value,
    topoConfig,
  })
  handleClose()
  showSuccessSaveMessage()
}

const handleClose = (done: () => void | undefined) => {
  visible.value = false
  if (done) done()
}

const show = async (_businessName: string) => {
  businessName.value = _businessName

  await loadTopoData(_businessName)
  visible.value = true
}

defineExpose({
  show,
})
</script>
